/******************************************************************************
 * 
 *Taylor Chan's works,just for practice!
 * 
 *****************************************************************************/

package com.cq.thinkinjava.concurrent.cancelthread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 中止线程的方式一，使用一个标志位，死循环的方式
 * 
 * @author Taylor Chan
 * @since 1.0
 * @version 2012-7-25 Taylor Chan Creat
 */
public class CancelThread {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            exec.execute(new Entrance(i));
        }
        try {
            TimeUnit.MILLISECONDS.sleep(3000L);
        } catch (InterruptedException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        Entrance.canceled();
        exec.shutdown();
        try {// 等待线程池中的所有任务在超时时间内完成，若完成返回true
            if (!exec.awaitTermination(250L, TimeUnit.MILLISECONDS)) {
                System.out.println("some task were not terminated");
            }
        } catch (InterruptedException e) {
            // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
            e.printStackTrace();
        }
        System.out.println("Total: " + Entrance.getTotalCount());
        System.out.println("Sum of Entrances: " + Entrance.sumEntrance());
    }
    
}

/**
 * @author Taylor Chan
 * @since 1.0
 * @version 2012-7-25 Taylor Chan Creat
 */
class Count {
    
    private int count = 0;
    
    private final Random rand = new Random(47);
    
    public synchronized int increment() {
        int temp = count;
        if (rand.nextBoolean())
            Thread.yield();
        return count = (++temp);
    }
    
    public synchronized int getValue() {
        return count;
    }
}

/**
 * 入口类，用于记录入口进入的人数 count是多个入口总的人数， 本类模拟的相当于一个计数器，可以有多个感知点，实时的反应多个感知点汇总的结果
 * 
 * @author Taylor Chan
 * @since 1.0
 * @version 2012-7-25 Taylor Chan Creat
 */
class Entrance implements Runnable {
    
    /**
     * 记录多个Entrance总数，多个线程需要对其操作，所以其自增需要同步
     */
    private static Count count = new Count();
    
    private static List<Entrance> entrances = new ArrayList<Entrance>();
    
    /**
     * 记录人数的属性
     */
    private int number;
    
    private final int id;
    
    private final Lock lock = new ReentrantLock();
    
    /**
     * 线程是否中止的标志位
     */
    private static volatile boolean canceled = false;
    
    public static void canceled() {
        canceled = true;
    }
    
    /**
     * @param id
     */
    public Entrance(int id) {
        // TODO 自动生成构造函数存根注释，构造函数实现时请删除此注释
        this.id = id;
        entrances.add(this);
    }
    
    /**
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        
        while (!canceled) {// number和count都自增一个
            lock.lock();
            try {
                ++number;
            } finally {
                lock.unlock();
            }
            System.out.println(this + " total: " + count.increment());
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                // TODO 自动生成异常捕获块存根注释，块实现时请删除此注释
                e.printStackTrace();
                System.out.println("sleep interrupted");
            }
        }
        System.out.println("Stopping " + this);
    }
    
    public synchronized int getValue() {
        return number;
    }
    
    @Override
    public String toString() {
        return "Entrance " + id + ": " + getValue();
    }
    
    public static int getTotalCount() {
        return count.getValue();
    }
    
    public static int sumEntrance() {
        int sum = 0;
        for (Entrance entrance : entrances) {
            sum += entrance.getValue();
        }
        return sum;
    }
}
